
namespace UMC.Proxy;
using System;
using System.Collections.Specialized;
using System.IO;
using System.Net;
using System.Net.Security;
using System.Net.Sockets;
using System.Security.Authentication;
using UMC.Net;

public class HttpsMimeSocket : HttpMime
{

    public override string Scheme => "https";

    public HttpsMimeSocket(System.IO.Stream stream, String ip)
    {
        this._stream = stream;
        this.ActiveTime = UMC.Data.Utility.TimeSpan();

        this.pid = stream.GetHashCode();

        this._Host = "127.0.0.1";

        this._remoteIpAddress = ip;

        HttpMimeServier.httpMimes.TryAdd(pid, this);
        Read();

    }
    Stream _stream;
    int pid = 0;

    public override int Id => pid;
    String _remoteIpAddress, _Host;
    public override String Host => _Host;
    public override String RemoteIpAddress => _remoteIpAddress;

    public override void Write(byte[] buffer, int offset, int count)
    {
        if (isDispose == false)
        {
            try
            {
                _stream.Write(buffer, offset, count);
            }
            catch
            {
                this.Dispose();
            }
        }
    }

    bool isDispose = false;
    public override void Dispose()
    {

        if (isDispose == false)
        {
            isDispose = true;
            if (this._data != null)
            {
                System.Buffers.ArrayPool<byte>.Shared.Return(this._data);
                _data = null;
            }
            try
            {
                if (this.Request is IDisposable)
                {
                    ((IDisposable)this.Request).Dispose();
                }
                _stream.Close();
                _stream.Dispose();
            }
            catch
            {

            }
        }
        HttpMimeServier.httpMimes.TryRemove(pid, out var _);

    }


    byte[] _data = System.Buffers.ArrayPool<byte>.Shared.Rent(0x600);


    async void Read()
    {
        int size = 0;
        try
        {
            while ((size = await _stream.ReadAsync(this._data, 0, this._data.Length)) > 0)
            {
                this.ActiveTime = UMC.Data.Utility.TimeSpan();
                if (this.Request == null)
                {
                    this.Request = new HttpMimeRequest(this);
                }
                var req = this.Request;
                req.Receive(this._data, 0, size);

                if (req.IsHttpFormatError)
                {
                    break;
                }

            }
        }
        catch
        {
            // this.Dispose();
            // return;
        }
        this.Dispose();

    }

}
